package com.cci.kangdao.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.common.WorkOrderStatusException;
import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMResponeEntity;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dao.model.WorkOrderT;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.NoticeService;
import com.cci.kangdao.service.OrderManageService;
import com.cci.kangdao.utilTool.Dictionaries;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.utilTool.OrderGenerateUtil;
import com.cci.kangdao.utilTool.ParameterTool;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("OrderManageService")
public class OrderManageServiceImpl implements OrderManageService {

	@Resource
	private CRMPlatformServiceDao platformServiceDao;

	@Autowired
	private RedisClientUtils redisClientUtils;

	@Autowired
	private NoticeService noticeService;

	@Autowired
	private ServiceStationDao serviceStationDao;

	@Autowired
	private OrderManageDao orderManageDao;

	@Autowired
	private WorkOrderTDao workOrderTDao;

	@Autowired
	private WorkOrderRepairDao workOrderRepairDao;

	@Autowired
	private UserTDao userTDao;

	@Autowired
	private WorkOrderFlowTDao workOrderFlowTDao;

	@Autowired
	private CompanyTDao companyTDao;

	private Logger log = Logger.getLogger(this.getClass().getName());
	/**
	 * 待400审核-400回访/诊断中/继续服务、待400主管审核
	 */
	private static final String MSG_TO_APPROVAL = "您有工单待审核，工单号%s，请处理。";
	/**
	 * 待服务商接单
	 */
	private static final String MSG_TO_NEWORDER = "您有新工单信息，工单号%s，请尽快处理。";
	/**
	 * 400已关闭
	 */
	private static final String MSG_TO_CLOSE = "您有工单被关闭，工单号%s，请查看。";
	/**
	 * 待派服务技师
	 */
	private static final String MSG_TO_ASSIGN_CUSTOMER = "您的工单已有服务商接单，工单号%s，请查看。";
	/**
	 * 待派服务技师
	 */
	private static final String MSG_TO_ASSIGN_STATION = "您有新的工单待指派，工单号%s，请尽快处理。";
	/**
	 * 400审核不通过-工单驳回
	 */
	private static final String MSG_TO_AUDITFAILED_CUSTOMER = "您有工单待更新，工单号%s，请尽快处理。";
	/**
	 * 400审核不通过-工单驳回
	 */
	private static final String MSG_TO_AUDITFAILED_STATION = "您有工单待更新，工单号%s，请尽快处理。";
	/**
	 * 待用户评价-400远程解决
	 */
	private static final String MSG_TO_RESOLVE_REMOTE_CUSTOMER = "您的工单远程服务已经完成，工单号%s，请查看。";

	@Override
	@Transactional
	public ModelAndView returnVisit(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");

		UserT user = UserThreadLocal.get();
		String currentTime = LocalTimeUtil.getRealCurrentTime();

		//获取工单信息
		Map<String, Object> orderMap = workOrderTDao.getOrderById(MapUtils.getLong(map, "OrderId"));

		//校验必填参数是否为空
		if(null == map.get("IsServicecompleted") || null == map.get("OrderId") || null == map.get("UpdateTime")) {
			ParameterTool.writeResponse(response, SMSEnum.type17.getIndex(),SMSEnum.type17.getName());
			return null;
		}

		//是否服务完成
		int isServicecompleted = MapUtils.getIntValue(map, "IsServicecompleted");
		String ConfirmModifyTime = MapUtils.getString(map, "ConfirmModifyTime");

		if (MapUtils.getInteger(orderMap, "OrderChannel") == 109) {
			if(null == map.get("ConfirmModifyTime")){
				ParameterTool.writeResponse(response, SMSEnum.type17.getIndex(),SMSEnum.type17.getName());
				return null;
			}
			long orderId = MapUtils.getLong(map, "OrderId");
			Map<String, Object> startPointMap = workOrderFlowTDao.getWorkOrderFlowByOrderIdAndStatus(orderId, 12);
			String CreateTime = MapUtils.getString(startPointMap, "CreateTime");
			if (!LocalTimeUtil.isBefore(ConfirmModifyTime, currentTime)) {
				ParameterTool.writeResponse(response,  SMSEnum.type601.getIndex(),SMSEnum.type601.getName());
				return null;
			}
			if (!LocalTimeUtil.isBefore(CreateTime, ConfirmModifyTime)) {
				ParameterTool.writeResponse(response,  SMSEnum.type602.getIndex(),SMSEnum.type602.getName());
				return null;
			}
		}
		int count = 0;
		map.put("CurrentTime", currentTime);
		map.put("UpdatorId", user.getId());


		map.put("OrderStatus", Dictionaries.OrderStatus_14.getIndex());

		int orderChannel = MapUtils.getIntValue(orderMap, "OrderChannel");

		if(orderChannel == 109){
			map.put("ConfirmModifyTime", ConfirmModifyTime);
			/**
			 * 3.1.0 CCEC 400回访优化
			 * CCEC 400回访结果为否,则该单状态回退到“维修中”
			 */
			if(isServicecompleted == 0) {
				map.put("ConfirmModifyTime", null);
				map.put("OrderStatus", Dictionaries.OrderStatus_12.getIndex());
			}

			count = orderManageDao.updateOrderStatus4ManagerCcec(map);
		}else{
			count = orderManageDao.updateOrderStatus4Manager(map);
		}
		//更新工单状态
		if(count == 0) {
			log.error("工单状态异常，需刷新APP");
			throw new WorkOrderStatusException();
		}
		//记录操作记录
		saveOperation(map, user.getId(), "400回访", currentTime);

		//根据是否完成服务进行业务处理
		if(isServicecompleted == 0) {
			/**
			 * 3.1.0 CCEC 400回访优化
			 * CCEC 400回访结果为否,同步工单状态到CRM，不再生成新的服务工单
			 */
			if(orderChannel == 109){
				// 同步服务工单状态到crm
				syncOrderStatusForCCEC(map, orderMap, user, currentTime);
			}else {
				//如果服务未完成，则需要同步旧工单的工单状态到CCSS
				syncOldOrderStatusToCCSS(map, orderMap, user, currentTime);
				//如果服务未完成，则需要生成新工单
				dealWithNewOrder(map, orderMap, user, currentTime);
			}
		} else {
			//整理工单信息符合CRM接口规范
			Map<String, Object> crmMap = buildData4SyncOrderStatus(orderMap, user);
			Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(MapUtils.getLong(orderMap, "ServiceStationId"),MapUtils.getLongValue(orderMap, "OrderChannel"));
			crmMap.put("stationNo", sSRepair.get("BusinessNo"));
			crmMap.put("phoneIMEI", MapUtils.getString(map, "IMEI"));
			crmMap.put("actionTime", currentTime);
			crmMap.put("billStatus", Dictionaries.OrderStatus_14.getIndex());
            crmMap.put("returnVisitTime", currentTime);
			//同步CRM接口
			CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm("CCEC", platformServiceDao, redisClientUtils, crmMap,null);
			//如果响应异常，则给用户提醒，业务流程结束
			if(CRMres.getStatus() != 0) {
				log.error("400回访调用CCSS接口同步工单状态异常，状态："+CRMres.getStatus()+"，异常信息:"+CRMres.getMessage());
			}
		}

		ParameterTool.writeSuccessResponse(response);
		return null;
	}


	/**
	 * 3.1.0 CCEC 400回访优化
	 * CCEC 400回访结果为否,同步工单状态到CRM，不再生成新的服务工单
	 */
	public void syncOrderStatusForCCEC(Map<String, Object> map, Map<String, Object> orderMap, UserT userT,String currentTime) {

		Map<String, Object> parameters1 = new HashMap<>();

		parameters1.put("orderNo", orderMap.get("OrderNo"));
		parameters1.put("billStatus", map.get("OrderStatus"));
		parameters1.put("actionTime",currentTime);
		parameters1.put("directorName",userT.getContact());
		parameters1.put("directorPhone",userT.getPhone());
		parameters1.put("positionLat",map.get("LocLat"));
		parameters1.put("positionLon",map.get("LocLon"));
		parameters1.put("phoneIMEI",MapUtils.getString(map, "IMEI"));
		parameters1.put("imei", MapUtils.getString(map, "IMEI"));
		parameters1.put("location",map.get("Location"));
		parameters1.put("CCSSComplainerOrderNo",orderMap.get("OrderNoCrm"));
		parameters1.put("CCSSOrderNo",orderMap.get("CCSSOrderNo"));
		parameters1.put("customerName",orderMap.get("CustomerName"));
		parameters1.put("customerPhone",orderMap.get("CustomerPhone"));
		parameters1.put("customerCompany",orderMap.get("CustomerCompanyName"));
		parameters1.put("faultDesc",orderMap.get("CustomerComplaint"));

		Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(MapUtils.getLongValue(orderMap, "ServiceStationId"), MapUtils.getLongValue(orderMap, "OrderChannel"));
		if(MapUtils.isNotEmpty(sSRepair)){
			parameters1.put("stationNo",sSRepair.get("BusinessNo"));
			parameters1.put("stationName",sSRepair.get("StationName"));
		}else{
			parameters1.put("stationNo","");
			parameters1.put("stationName","");
		}
		try {
			CRMResponeEntity crmResponeEntity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm(companyTDao.getCompanyInfoByCompanyID(MapUtils.getLongValue(orderMap, "OrderChannel")).getCompanyNo(),platformServiceDao,redisClientUtils,parameters1,null);
			if(crmResponeEntity.getStatus() != 0) {
				log.error("同步工单状态至CRM失败!状态:" + crmResponeEntity.getStatus() + ",错误信息:" + crmResponeEntity.getMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
		}

	}



	// 400回访同步旧工单的工单状态到CCSS系统
	public void syncOldOrderStatusToCCSS(Map<String, Object> map, Map<String, Object> orderMap, UserT user, String currentTime) {

		// 调用2.2.3 APP系统同步旧工单状态信息到CRM系统
		Map<String, Object> parameters1 = new HashMap<>();
		parameters1.put("orderNo",orderMap.get("OrderNo"));
		parameters1.put("billStatus",Dictionaries.OrderStatus_14.getIndex());
		parameters1.put("actionTime",currentTime);
		parameters1.put("directorName",user.getContact());
		parameters1.put("directorPhone",user.getPhone());
		parameters1.put("positionLat",map.get("LocLat"));
		parameters1.put("positionLon",map.get("LocLon"));
		parameters1.put("phoneIMEI",MapUtils.getString(map, "IMEI"));
		parameters1.put("location",map.get("Location"));


		Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(MapUtils.getLong(orderMap, "ServiceStationId"),MapUtils.getLongValue(orderMap, "OrderChannel"));
		parameters1.put("stationNo",sSRepair.get("BusinessNo"));
		parameters1.put("CCSSComplainerOrderNo",orderMap.get("OrderNoCrm"));
		parameters1.put("CCSSOrderNo",orderMap.get("CCSSOrderNo"));
		parameters1.put("customerName",orderMap.get("CustomerName"));
		parameters1.put("customerPhone",orderMap.get("CustomerPhone"));
		parameters1.put("customerCompany",orderMap.get("CustomerCompanyName"));
		parameters1.put("faultDesc",orderMap.get("CustomerComplaint"));


        parameters1.put("returnVisitTime",LocalTimeUtil.getRealCurrentTime());
		try {
			CRMResponeEntity crmResponeEntity = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm("CCEC",platformServiceDao,redisClientUtils,parameters1,null);
			if(crmResponeEntity.getStatus() != 0) {
				log.error("同步工单状态至CRM失败!状态:" + crmResponeEntity.getStatus() + ",错误信息:" + crmResponeEntity.getMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
		}

	}


	public void dealWithNewOrder(Map<String, Object> map, Map<String, Object> orderMap, UserT user, String currentTime) {
		Map<String, Object> newOrder = createNewOrder(orderMap, Dictionaries.OrderStatus_24.getIndex(), MapUtils.getLong(orderMap, "ServiceStationId"));
		newOrder.put("ServiceStationId",0);
		newOrder.put("CCSSOrderNo", "");
		int newCount = workOrderRepairDao.CreateWorkOrder(newOrder);
		if(newCount == 0) {
			log.error("400回访服务未完成，新工单创建失败！");
			throw new RuntimeException();
		}

		String ccssOrderNo = "";
		//整理工单信息符合CRM接口规范
		Map<String, Object> crmMap = buildData4SyncOrderStatus(newOrder, user);
		Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(MapUtils.getLong(orderMap, "ServiceStationId"),MapUtils.getLongValue(orderMap, "OrderChannel"));
		crmMap.put("stationNo", sSRepair.get("BusinessNo"));
		crmMap.put("phoneIMEI", MapUtils.getString(map, "IMEI"));
		crmMap.put("actionTime", currentTime);
		crmMap.put("planMileage", MapUtils.getFloatValue(map, "Distance"));
		crmMap.put("billStatus", Dictionaries.OrderStatus_24.getIndex());
		crmMap.put("CCSSOrderNo", "");
		//同步CRM接口
		CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm("CCEC", platformServiceDao, redisClientUtils, crmMap,null);
		//如果响应异常，则给用户提醒，业务流程结束
		if(CRMres.getStatus() != 0) {
			log.error("400回访调用CCSS接口同步工单状态异常，状态："+CRMres.getStatus()+"，异常信息:"+CRMres.getMessage());
		}

		//更新新工单的CCSSOrderNo--从响应中取CCSSOrderNo
		if(CRMres.getData().containsKey("CCSSOrderNo")){
			ccssOrderNo = CRMres.getData().getString("CCSSOrderNo");
		}

		orderManageDao.updateRelOrderId(MapUtils.getLong(newOrder, "OrderId"), MapUtils.getLong(map, "OrderId"));

		saveOperation(newOrder, user.getId(), "400回访", currentTime);

		//记录负责人
		Map<String, Object> pMap = new HashMap<>(); //存放服务人数据
		pMap.putAll(map);
		pMap.put("ProcessorId", user.getId());
		pMap.put("CreateTime", currentTime);
		pMap.remove("UpdateTime");
		pMap.put("OrderId", MapUtils.getLong(newOrder, "OrderId"));
		pMap.put("OrderStatus", Dictionaries.OrderStatus_24.getIndex());

		map.put("ServiceStationId", MapUtils.getLong(orderMap, "ServiceStationId"));
		map.put("OrderChannel", MapUtils.getLong(orderMap, "OrderChannel"));
		List<Map<String,Object>> principalList = workOrderRepairDao.getAreaManager(map);

		for(Map<String,Object> principal : principalList) {
			pMap.put("PrincipalId", principal.get("ID"));
			pMap.put("IsPrincipal", 1);

			workOrderRepairDao.savePrincipal(pMap);
		}

		String orderNo = MapUtils.getString(newOrder, "OrderNo");

		String msgNew = String.format(MSG_TO_APPROVAL, StringUtils.isBlank(ccssOrderNo)? orderNo: orderNo + "（FW号" + ccssOrderNo + "）");

		Long orderIdNew = MapUtils.getLong(newOrder, "OrderId");

		//推送消息--新工单
		for(Map<String,Object> principal : principalList) {
			noticeService.push(18, 1, orderIdNew, MapUtils.getLong(principal, "ID"), MapUtils.getString(principal, "UserName"), "新消息提醒", msgNew, msgNew, user.getId());
			noticeService.sendSMS(18, 1, orderIdNew, MapUtils.getLong(principal, "ID"), MapUtils.getString(principal, "Phone"), msgNew, user.getId());
		}
	}

	@Override
	@Transactional
	public ModelAndView resolveRemoteCCEC(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		UserT user = UserThreadLocal.get();
		String currentTime = LocalTimeUtil.getRealCurrentTime();

		map.put("Creator", user.getId());
		map.put("CreateTime", currentTime);
		//记录远程解决方案
		orderManageDao.insertResolveRemoteRecord(map);

		map.put("OrderStatus", Dictionaries.OrderStatus_33.getIndex());
		map.put("UpdatorId", user.getId());
		map.put("CurrentTime", currentTime);
		//更新工单信息   2.4.0页面增加可以修改报修人类型和故障原因字段
		int count = orderManageDao.updateOrderStatus4ResolveRemote(map);

		if(count == 0) {
			JSONObject jsb = new JSONObject();
			jsb.put("status", SMSEnum.type21.getIndex());
			jsb.put("msg", SMSEnum.type21.getName());
			throw new WorkOrderStatusException(jsb.toString());
		}

		//获取工单信息
		map.put("ID", MapUtils.getLong(map, "OrderId"));
		WorkOrderT order = workOrderTDao.getWorkOrderTById(map);

		//整理工单信息符合CRM接口规范
		Map<String, Object> crmMap = buildData4SyncOrderStatus(order, user);
		if(order.getServiceStationId() != 0) {
			Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(order.getServiceStationId(),order.getOrderChannel());
			crmMap.put("stationNo", sSRepair.get("BusinessNo"));
		}
		crmMap.put("phoneIMEI", MapUtils.getString(map, "IMEI"));
		crmMap.put("actionTime", currentTime);
		crmMap.put("billStatus", Dictionaries.OrderStatus_33.getIndex());
		crmMap.put("complainOrderType", MapUtils.getString(map, "ComplaintOrderType"));
        crmMap.put("faultReason", MapUtils.getString(map, "FaultReason"));
        crmMap.put("repairerType", MapUtils.getString(map, "RepairerType"));
		//同步CRM接口
		CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi().relyOrderStatusToCrm("CCEC", platformServiceDao, redisClientUtils, crmMap);
		//如果响应异常，则给用户提醒，业务流程结束
		if(CRMres.getStatus() != 0) {
			JSONObject jsb = new JSONObject();
			jsb.put("status", SMSEnum.type600.getIndex());
			jsb.put("msg", SMSEnum.type600.getName());
			throw new WorkOrderStatusException(jsb.toString());
		}

		//记录操作记录
		saveOperation(map, user.getId(), "400远程解决", currentTime);

		List<UserT> userList = orderManageDao.getManagerList();
		if(CollectionUtils.isNotEmpty(userList)) {
			//记录下一步处理人
			map.put("ProcessorId", user.getId());
			map.remove("UpdateTime");
			for(UserT principal: userList) {
				map.put("PrincipalId", principal.getId());
				map.put("IsPrincipal", 1);
				workOrderRepairDao.savePrincipal(map);
			}

			String ccssOrderNo = order.getCCSSOrderNo();

			String msg = String.format(MSG_TO_APPROVAL, StringUtils.isBlank(ccssOrderNo)? order.getOrderNo(): order.getOrderNo() + "（FW号" + ccssOrderNo + "）");
			//推送消息
			for(UserT principal: userList) {
				//TODO 消息推送
				noticeService.push(18, 1, order.getId(), principal.getId(), principal.getUserName(), "新消息提醒", msg, msg, user.getId());
				noticeService.sendSMS(18, 1, order.getId(), principal.getId(), principal.getPhone(), msg, user.getId());
			}
		}

//		//作废400已处理状态记录
//		orderManageDao.updatePrincipalStatus(MapUtils.getLong(map, "OrderId"), Dictionaries.OrderStatus_23.getIndex());

		//同步远程解决数据到CRM
		CRMApiUtils.getCRMServiceApi().syncRemoteSolution("CCEC", bulidResolveRemoteData(map, order));


		ParameterTool.writeSuccessResponse(response);
		return null;
	}

	@Override
	@Transactional
	public ModelAndView reassignServiceStation(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		JSONObject obj = new JSONObject();

		//校验必填参数
		if(MapUtils.getLong(map, "OrderId") == 0 || MapUtils.getLong(map, "StationId") == 0) {
			ParameterTool.writeResponse(response, SMSEnum.type17.getIndex(),SMSEnum.type17.getName());
			return null;
		}

		//获取工单信息和服务站信息
		Map<String, Object> orderMap = workOrderTDao.getOrderById(MapUtils.getLong(map, "OrderId"));
		//判断工单状态
		int orderStatus = 0;
		int orderSource = MapUtils.getIntValue(orderMap, "OrderSource");
		if(orderSource == 0 || orderSource == 2) {
			orderStatus = Dictionaries.OrderStatus_04.getIndex(); //待服务商接单
		} else {

			if (MapUtils.getLongValue(orderMap, "ServiceStationId",0)<1){ // 这种情况是1 无法开始维修 2 服务商拒单 3 400回访服务未完成

				orderStatus = Dictionaries.OrderStatus_04.getIndex(); //待服务商接单

			}else
			{
				if(MapUtils.getLongValue(orderMap, "ServiceStationId") == MapUtils.getLongValue(map, "StationId")) {
					orderStatus = Dictionaries.OrderStatus_06.getIndex(); //待派服务技师
				} else {
					orderStatus = Dictionaries.OrderStatus_29.getIndex(); //400已关闭
				}
			}

		}
		map.put("OrderStatus", orderStatus);
		//根据工单状态进行业务处理
		if(orderStatus == Dictionaries.OrderStatus_04.getIndex()) {
			//用户APP报修或者用户400报修，待服务商接单
			obj = assignServiceStation(map, orderMap, orderStatus);
		} else if(orderStatus == Dictionaries.OrderStatus_06.getIndex()) {
			//指派服务站和报单服务站一致
			obj = assignEngineer(map, orderMap, orderStatus);
		} else if(orderStatus == Dictionaries.OrderStatus_29.getIndex()) {
			//改派服务站
			obj = reassineServiceStation(map, orderMap);
		}

//		//作废400已处理状态记录
//		orderManageDao.updatePrincipalStatus(MapUtils.getLong(map, "OrderId"), Dictionaries.OrderStatus_23.getIndex());

		ParameterTool.writeResponse(response, obj.toString());
		return null;
	}

	@Transactional
	public JSONObject assignServiceStation(Map<String, Object> map, Map<String, Object> order, int status) {
		JSONObject jsb = new JSONObject();

		//整理工单信息符合CRM接口规范
		UserT user = UserThreadLocal.get();
		String currentTime = LocalTimeUtil.getRealCurrentTime();

		map.put("UpdatorId", user.getId());
		map.put("CurrentTime", currentTime);
		//2.4.0ccec新增加报修人类型和故障原因
		int count = orderManageDao.updateOrderStatus4assignSS(map);

		if(count == 0) {
			log.error("工单状态异常，需刷新APP");
			jsb.put("status", SMSEnum.type21.getIndex());
			jsb.put("msg", SMSEnum.type21.getName());
			throw new WorkOrderStatusException(jsb.toString());
		}

		//整理工单信息符合CRM接口规范
		Map<String, Object> crmMap = buildData4SyncOrderStatus(order, user);
		Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(MapUtils.getLongValue(map, "StationId"),MapUtils.getLongValue(order, "OrderChannel"));
		crmMap.put("stationNo", sSRepair.get("BusinessNo"));
		crmMap.put("phoneIMEI", MapUtils.getString(map, "IMEI"));
		crmMap.put("actionTime", currentTime);
		crmMap.put("planMileage", MapUtils.getFloatValue(map, "Distance"));
		crmMap.put("complainOrderType", MapUtils.getString(map, "ComplaintOrderType"));
        crmMap.put("faultReason", MapUtils.getString(map, "FaultReason"));
        crmMap.put("repairerType", MapUtils.getString(map, "RepairerType"));
		//如果是待派服务技师状态，需要先同步指派服务商信息到CCSS
		crmMap.put("billStatus", status == Dictionaries.OrderStatus_06.getIndex()? Dictionaries.OrderStatus_04.getIndex(): status);
		//同步CRM接口
		CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi().relyOrderStatusToCrm("CCEC", platformServiceDao, redisClientUtils, crmMap);
		//如果响应异常，则给用户提醒，业务流程结束
		if(CRMres.getStatus() != 0) {
			log.error("400远程解决调用CCSS接口同步工单状态异常，状态："+CRMres.getStatus()+"，异常信息:"+CRMres.getMessage());
			jsb.put("status", SMSEnum.type600.getIndex());
			jsb.put("msg", SMSEnum.type600.getName());
			throw new WorkOrderStatusException(jsb.toString());
		}
		//CCSSOrderNo 在OrderStatus_04同步后由CRM返回
		String ccssOrderNo = "";
		if(CRMres.getData().containsKey("CCSSOrderNo")){
			ccssOrderNo = CRMres.getData().getString("CCSSOrderNo");
		}

		//如果是待派服务技师，需要先同步待服务商接单状态到CCSS，然后再同步待派服务技师状态
		if(status == Dictionaries.OrderStatus_06.getIndex()) {
			crmMap.put("billStatus", status);
			crmMap.put("CCSSOrderNo", ccssOrderNo);
			//同步CRM接口
			CRMres = CRMApiUtils.getCRMServiceApi().relyOrderStatusToCrm("CCEC", platformServiceDao, redisClientUtils, crmMap);
			//如果响应异常，则给用户提醒，业务流程结束
			if(CRMres.getStatus() != 0) {
				log.error("400远程解决调用CCSS接口同步工单状态异常，状态："+CRMres.getStatus()+"，异常信息:"+CRMres.getMessage());
				jsb.put("status", SMSEnum.type600.getIndex());
				jsb.put("msg", SMSEnum.type600.getName());
				throw new WorkOrderStatusException(jsb.toString());
			}
		}

		//记录操作记录
		saveOperation(map, user.getId(), "400指派服务站", currentTime);

		//指派负责人
		map.put("ProcessorId", user.getId());
		map.put("CreateTime", currentTime);
		map.remove("UpdateTime");

		List<UserT> principalList = userTDao.getStationMasterListByServiceStationId(MapUtils.getLong(map, "StationId"));
		for(UserT principal : principalList) {
			map.put("PrincipalId", principal.getId());
			map.put("IsPrincipal", 1);
			workOrderRepairDao.savePrincipal(map);
		}

		String orderNo = MapUtils.getString(order, "OrderNo");
        // 服务站渠道
		int OrderChannel = MapUtils.getIntValue(order, "OrderChannel");
		String serviceSubtype = MapUtils.getString(order, "ServiceSubtype", "");
		String sellType = MapUtils.getString(order, "SellType", "");
		String msg = "";
		if(status == 4) {
			if(OrderChannel == 1){
				msg = "您有新工单信息，工单号" + orderNo + "，";
				msg = msg + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
				msg = msg + "请尽快处理！";
			} else {
				msg = String.format(MSG_TO_NEWORDER, StringUtils.isBlank(ccssOrderNo)? orderNo: orderNo + "（FW号" + ccssOrderNo + "）");
			}
		} else {
			if(OrderChannel == 1){
				msg = "您有新的工单待指派，工单号" + orderNo + "，";
				msg = msg + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
				msg = msg + "请尽快处理！";
			} else {
				msg = String.format(MSG_TO_ASSIGN_STATION, StringUtils.isBlank(ccssOrderNo)? orderNo: orderNo + "（FW号" + ccssOrderNo + "）");
			}

		}


		Long orderId = MapUtils.getLong(order, "ID");
		//消息推送
		for(UserT principal : principalList) {
			//TODO 消息推送
			noticeService.push(18, 1, orderId, principal.getId(), principal.getUserName(), "新消息提醒", msg, msg, user.getId());
			noticeService.sendSMS(18, 1, orderId, principal.getId(), principal.getPhone(), msg, user.getId());
		}

		jsb.put("status", 0);
		jsb.put("msg", "success");
		return jsb;
	}

	public JSONObject assignEngineer(Map<String, Object> map, Map<String, Object> order, int status) {
		JSONObject jsb = new JSONObject();

		jsb = assignServiceStation(map, order, status);

		//推送消息给用户
		if(null != MapUtils.getLong(order, "CustomerId")) {
			UserT principal = userTDao.selectById(MapUtils.getLong(order, "CustomerId"));

			String orderNo = MapUtils.getString(order, "OrderNo");

			String msg = String.format(MSG_TO_ASSIGN_CUSTOMER, orderNo);

			Long orderId = MapUtils.getLong(order, "ID");

			UserT user = UserThreadLocal.get();

			noticeService.push(18, 1, orderId, principal.getId(), principal.getUserName(), "新消息提醒", msg, msg, user.getId());
			noticeService.sendSMS(18, 1, orderId, principal.getId(), principal.getPhone(), msg, user.getId());
		}

		return jsb;
	}

	/**
	 * 改派服务站
	 * @param map APP传入数据
	 * @param order 旧工单数据
	 * @return
	 */
	@Transactional
	public JSONObject reassineServiceStation(Map<String, Object> map, Map<String, Object> order) {
		JSONObject jsb = new JSONObject();
		UserT user = UserThreadLocal.get();
		String currentTime = LocalTimeUtil.getRealCurrentTime();

		//更新旧工单数据
		map.put("UpdatorId", user.getId());
		map.put("CurrentTime", currentTime);
		//2.4.0ccec支持修改报修人类型和故障原因
		int count = orderManageDao.updateOrderStatus4reassignSS(map);

		if(count == 0) {
			log.error("工单状态异常，需刷新APP");
			jsb.put("status", SMSEnum.type21.getIndex());
			jsb.put("msg", SMSEnum.type21.getName());
			throw new WorkOrderStatusException(jsb.toString());
		}

		//创建新工单
		Long stationId = MapUtils.getLong(map, "StationId");
		Map<String, Object> newOrder = createNewOrder(order, 4, stationId);


		int newCount = workOrderRepairDao.CreateWorkOrder(newOrder);
		if(newCount == 0) {
			log.error("400改派服务站，新工单创建失败！");
			throw new RuntimeException();
		}

		String ccssOrderNo = "";
		//整理工单信息符合CRM接口规范
		Map<String, Object> crmMap = buildData4SyncOrderStatus(newOrder, user);
		Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(stationId,MapUtils.getLongValue(order, "OrderChannel"));
		crmMap.put("stationNo", sSRepair.get("BusinessNo"));
		crmMap.put("phoneIMEI", MapUtils.getString(map, "IMEI"));
		crmMap.put("actionTime", currentTime);
		crmMap.put("planMileage", MapUtils.getFloatValue(map, "Distance"));
		crmMap.put("complainOrderType", MapUtils.getString(map, "ComplaintOrderType"));
		crmMap.put("billStatus", 4);
        crmMap.put("faultReason", MapUtils.getString(map, "FaultReason"));
        crmMap.put("repairerType", MapUtils.getString(map, "RepairerType"));
		//同步CRM接口
		CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi().relyOrderStatusToCrm("CCEC", platformServiceDao, redisClientUtils, crmMap);
		//如果响应异常，则给用户提醒，业务流程结束
		if(CRMres.getStatus() != 0) {
			log.error("400远程解决调用CCSS接口同步工单状态异常，状态："+CRMres.getStatus()+"，异常信息:"+CRMres.getMessage());
			jsb.put("status", SMSEnum.type600.getIndex());
			jsb.put("msg", SMSEnum.type600.getName());
			throw new WorkOrderStatusException(jsb.toString());
		}

		//更新新工单的CCSSOrderNo--从响应中取CCSSOrderNo
		if(CRMres.getData().containsKey("CCSSOrderNo")){
			ccssOrderNo = CRMres.getData().getString("CCSSOrderNo");
		}
//		// 业务逻辑不做更新，已在接口更新
//		if(StringUtils.isNotBlank(ccssOrderNo)) {
//			orderManageDao.updateCCSSOrderNo(ccssOrderNo, MapUtils.getLong(newOrder, "OrderId"));
//		}

		orderManageDao.updateRelOrderId(MapUtils.getLong(newOrder, "OrderId"), MapUtils.getLong(map, "OrderId"));

		//记录处理人--旧工单
		saveOperation(map, user.getId(), "400改派服务站", currentTime);
		//记录处理人--新工单
		saveOperation(newOrder, user.getId(), "400改派服务站", currentTime);
		//记录负责人
		Map<String, Object> pMap = new HashMap<>(); //存放服务人数据
		pMap.putAll(map);
		pMap.put("ProcessorId", user.getId());
		pMap.put("CreateTime", currentTime);
		pMap.remove("UpdateTime");
		pMap.put("OrderId", MapUtils.getLong(newOrder, "OrderId"));
		pMap.put("OrderStatus", 4);
		List<UserT> principalList = userTDao.getStationMasterListByServiceStationId(MapUtils.getLong(pMap, "StationId"));
		for(UserT principal : principalList) {
			pMap.put("PrincipalId", principal.getId());
			pMap.put("IsPrincipal", 1);
			workOrderRepairDao.savePrincipal(pMap);
		}

		String orderNo = MapUtils.getString(newOrder, "OrderNo");
		int OrderChannel = MapUtils.getIntValue(newOrder, "OrderChannel");
		String serviceSubtype = MapUtils.getString(newOrder, "ServiceSubtype", "");
		String sellType = MapUtils.getString(newOrder, "SellType", "");
		String msgNew = "";
		if(OrderChannel == 1){
			msgNew = "您有新工单信息，工单号" + orderNo + "，";
			msgNew = msgNew + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
			msgNew = msgNew + "请尽快处理！";
		} else {
			msgNew = String.format(MSG_TO_NEWORDER, StringUtils.isBlank(ccssOrderNo)? orderNo: orderNo + "（FW号" + ccssOrderNo + "）");
		}

		Long orderIdNew = MapUtils.getLong(newOrder, "OrderId");

		//推送消息--新工单
		for(UserT principal : principalList) {
			noticeService.push(18, 1, orderIdNew, principal.getId(), principal.getUserName(), "新消息提醒", msgNew, msgNew, user.getId());
			noticeService.sendSMS(18, 1, orderIdNew, principal.getId(), principal.getPhone(), msgNew, user.getId());
		}

		//推送消息--旧工单
		List<UserT> leaders = userTDao.getStationMasterListByServiceStationId(MapUtils.getLong(order, "ServiceStationId"));
		String ccssOrderNoOld = MapUtils.getString(order, "CCSSOrderNo");
		String orderNoOld = MapUtils.getString(order, "OrderNo");
		String msgOld = String.format(MSG_TO_CLOSE, StringUtils.isBlank(ccssOrderNoOld)? orderNoOld: orderNoOld + "（FW号" + ccssOrderNoOld + "）");

		for(UserT leader : leaders) {
			noticeService.push(18, 1, MapUtils.getLong(order, "ID"), leader.getId(), leader.getUserName(), "新消息提醒", msgOld, msgOld, user.getId());
			noticeService.sendSMS(18, 1, MapUtils.getLong(order, "ID"), leader.getId(), leader.getPhone(), msgOld, user.getId());
		}

		jsb.put("status", 0);
		jsb.put("msg", "success");
		return jsb;
	}

	@Override
	@Transactional
	public ModelAndView closeOrderByManager(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");

		UserT user = UserThreadLocal.get();
		String currentTime = LocalTimeUtil.getRealCurrentTime();
		//更新工单状态
		map.put("OrderStatus", 28);
		map.put("UpdatorId", user.getId());
		map.put("CurrentTime", currentTime);
		int count = orderManageDao.updateOrderStatus4Manager(map);

		if(count == 0) {
			log.error("工单状态异常，需刷新APP");
			throw new WorkOrderStatusException();
		}
		//记录操作记录
		saveOperation(map, user.getId(), "400主管关闭工单", currentTime);

		//获取工单信息
		map.put("ID", MapUtils.getLong(map, "OrderId"));
		WorkOrderT order = workOrderTDao.getWorkOrderTById(map);

		//根据工单来源进行逻辑处理
		map.put("ProcessorId", user.getId());
		map.put("CreateTime", currentTime);
		map.remove("UpdateTime");

		//指派负责人
		long customerId = order.getCustomerId();
		map.put("PrincipalId", customerId);
		map.put("IsPrincipal", 1);
		workOrderRepairDao.savePrincipal(map);

		//消息推送
		if(customerId != 0) {
			UserT principal = userTDao.selectById(order.getCustomerId());

			//TODO 消息推送
			String msg = String.format(MSG_TO_RESOLVE_REMOTE_CUSTOMER, order.getOrderNo());
			noticeService.push(19, 1, order.getId(), principal.getId(), principal.getUserName(), "新消息提醒", msg, msg, user.getId());
			noticeService.sendSMS(19, 1, order.getId(), principal.getId(), principal.getPhone(), msg, user.getId());
		}

//		//作废400主管已处理状态记录
//		orderManageDao.updatePrincipalStatus(MapUtils.getLong(map, "OrderId"), Dictionaries.OrderStatus_33.getIndex());

		//整理工单信息符合CRM接口规范
		Map<String, Object> crmMap = buildData4SyncOrderStatus(order, user);
		if(order.getServiceStationId() != 0) {
			Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(order.getServiceStationId(),order.getOrderChannel());
			crmMap.put("stationNo", sSRepair.get("BusinessNo"));
		}
		crmMap.put("phoneIMEI", MapUtils.getString(map, "IMEI"));
		crmMap.put("actionTime", currentTime);
		crmMap.put("billStatus", Dictionaries.OrderStatus_28.getIndex());
		//同步CRM接口
		CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm("CCEC", platformServiceDao, redisClientUtils, crmMap,null);
		//如果响应异常，则给用户提醒，业务流程结束
		if(CRMres.getStatus() != 0) {
			log.error("400主管关闭工单调用CCSS接口同步工单状态异常，状态："+CRMres.getStatus()+"，异常信息:"+CRMres.getMessage());
		}

		ParameterTool.writeSuccessResponse(response);
		return null;
	}

	@Override
	@Transactional
	public ModelAndView continueService(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");

		UserT user = UserThreadLocal.get();
		String currentTime = LocalTimeUtil.getRealCurrentTime();
		//更新工单状态
		map.put("OrderStatus", 24);
		map.put("UpdatorId", user.getId());
		map.put("CurrentTime", currentTime);
		int count = orderManageDao.updateOrderStatus4Manager(map);

		if(count == 0) {
			log.error("工单状态异常，需刷新APP");
			throw new WorkOrderStatusException();
		}
		//记录操作记录
		saveOperation(map, user.getId(), "400主管继续服务", currentTime);

		//获取工单信息
		map.put("ID", MapUtils.getLong(map, "OrderId"));
		WorkOrderT order = workOrderTDao.getWorkOrderTById(map);

		//根据工单来源进行逻辑处理
		map.put("ProcessorId", user.getId());
		map.put("CreateTime", currentTime);
		map.remove("UpdateTime");

		//指派负责人
		List<Map<String,Object>> principalList = new ArrayList<>();
		long ssId = order.getServiceStationId();
		if(ssId == 0) {
			principalList = workOrderRepairDao.getCCECAreaManager(order.getOrderChannel());
		} else {
			map.put("ServiceStationId", ssId);
			map.put("OrderChannel", order.getOrderChannel());
			principalList = workOrderRepairDao.getAreaManager(map);
		}

		for(Map<String,Object> principal: principalList) {
			map.put("PrincipalId", principal.get("ID"));
			map.put("IsPrincipal", 1);
			workOrderRepairDao.savePrincipal(map);
		}

		String ccssOrderNo = order.getCCSSOrderNo();

		String msg = String.format(MSG_TO_APPROVAL, StringUtils.isBlank(ccssOrderNo)? order.getOrderNo(): order.getOrderNo() + "（FW号" + ccssOrderNo + "）");
		//推送消息
		for(Map<String,Object> principal: principalList) {
			//消息推送
			noticeService.push(18, 1, order.getId(), MapUtils.getLong(principal, "ID"), MapUtils.getString(principal, "UserName"), "新消息提醒", msg, msg, user.getId());
			noticeService.sendSMS(18, 1, order.getId(), MapUtils.getLong(principal, "ID"), MapUtils.getString(principal, "Phone"), msg, user.getId());
		}

//		//作废400主管已处理状态记录
//		orderManageDao.updatePrincipalStatus(MapUtils.getLong(map, "OrderId"), Dictionaries.OrderStatus_33.getIndex());

		//整理工单信息符合CRM接口规范
		Map<String, Object> crmMap = buildData4SyncOrderStatus(order, user);
		if(order.getServiceStationId() != 0) {
			Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(order.getServiceStationId(),order.getOrderChannel());
			crmMap.put("stationNo", sSRepair.get("BusinessNo"));
		}
		crmMap.put("phoneIMEI", MapUtils.getString(map, "IMEI"));
		crmMap.put("actionTime", currentTime);
		crmMap.put("billStatus", Dictionaries.OrderStatus_28.getIndex());
		CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi().syncOrderStatusToCrm("CCEC", platformServiceDao, redisClientUtils, crmMap,null);
		//如果响应异常，则给用户提醒，业务流程结束
		if(CRMres.getStatus() != 0) {
			log.error("400主管继续服务调用CCSS接口同步工单状态异常，状态："+CRMres.getStatus()+"，异常信息:"+CRMres.getMessage());
		}

		ParameterTool.writeSuccessResponse(response);
		return null;
	}

	@Override
	@Transactional
	public ModelAndView auditFailed(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse)map.get("response");
		JSONObject jsb = new JSONObject();
		UserT user = UserThreadLocal.get();
		String currentTime = LocalTimeUtil.getRealCurrentTime();

		//更新工单状态
		map.put("OrderStatus", 25);
		map.put("UpdatorId", user.getId());
		map.put("CurrentTime", currentTime);
		//2.4.0ccec支持修改报修人类型和故障原因
		int count = orderManageDao.updateOrderStatus4AuditFailed(map);

		if(count == 0) {
			jsb.put("status", SMSEnum.type21.getIndex());
			jsb.put("msg", SMSEnum.type21.getName());
			throw new WorkOrderStatusException(jsb.toString());
		}

		//获取工单信息
		map.put("ID", MapUtils.getLong(map, "OrderId"));
		WorkOrderT order = workOrderTDao.getWorkOrderTById(map);

		//整理工单信息符合CRM接口规范
		Map<String, Object> crmMap = buildData4SyncOrderStatus(order, user);
		if(order.getServiceStationId() != 0) {
			Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(order.getServiceStationId(),order.getOrderChannel());
			crmMap.put("stationNo", sSRepair.get("BusinessNo"));
		}
		crmMap.put("phoneIMEI", MapUtils.getString(map, "IMEI"));
		crmMap.put("actionTime", currentTime);
		crmMap.put("complainOrderType", MapUtils.getString(map, "ComplaintOrderType"));
		crmMap.put("billStatus", Dictionaries.OrderStatus_25.getIndex());
        crmMap.put("faultReason", MapUtils.getString(map, "FaultReason"));
        crmMap.put("repairerType", MapUtils.getString(map, "RepairerType"));
		//同步工单状态到CRM
		CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi().relyOrderStatusToCrm("CCEC", platformServiceDao, redisClientUtils, crmMap);

		if(CRMres.getStatus() != 0) {
			log.error("400远程解决调用CCSS接口同步工单状态异常，状态："+CRMres.getStatus()+"，异常信息:"+CRMres.getMessage());
			jsb.put("status", SMSEnum.type600.getIndex());
			jsb.put("msg", SMSEnum.type600.getName());
			throw new WorkOrderStatusException(jsb.toString());
		}

		//记录操作记录
		saveOperation(map, user.getId(), "400审核不通过", currentTime);
		//根据工单来源进行逻辑处理
		map.put("ProcessorId", user.getId());
		map.put("CreateTime", currentTime);
		map.remove("UpdateTime");
		if(order.getOrderSource() == 0) {
			//用户APP报单
			UserT principal = userTDao.selectById(order.getCustomerId());
			if(null != principal) {
				map.put("PrincipalId", principal.getId());
				map.put("IsPrincipal", 1);
				workOrderRepairDao.savePrincipal(map);
			}

			//消息推送
			String msg = String.format(MSG_TO_AUDITFAILED_CUSTOMER, order.getOrderNo());
			noticeService.push(19, 1, order.getId(), principal.getId(), principal.getUserName(), "新消息提醒", msg, msg, user.getId());
			noticeService.sendSMS(19, 1, order.getId(), principal.getId(), principal.getPhone(), msg, user.getId());

		} else if(order.getOrderSource() == 1) {
			//服务商APP报单
			List<UserT> principalList = userTDao.getStationMasterListByServiceStationId(order.getServiceStationId());
			for(UserT principal: principalList) {
				map.put("PrincipalId", principal.getId());
				map.put("IsPrincipal", 1);
				workOrderRepairDao.savePrincipal(map);
			}

			//消息推送
			String msg = String.format(MSG_TO_AUDITFAILED_STATION, order.getOrderNo());
			for(UserT principal: principalList) {
				noticeService.push(19, 1, order.getId(), principal.getId(), principal.getUserName(), "新消息提醒", msg, msg, user.getId());
				noticeService.sendSMS(19, 1, order.getId(), principal.getId(), principal.getPhone(), msg, user.getId());
			}

		}

//		//作废400主管已处理状态记录
//		orderManageDao.updatePrincipalStatus(MapUtils.getLong(map, "OrderId"), Dictionaries.OrderStatus_23.getIndex());

		ParameterTool.writeSuccessResponse(response);
		return null;
	}

	/**
	 * 同步工单状态数据整理
	 * @param obj
	 * @return
	 */
	public Map<String, Object> buildData4SyncOrderStatus(Object obj, UserT user) {
		Map<String, Object> crmMap = new HashMap<>();

		if(obj instanceof Map) {
			buildData4SyncOrderStatusFromMap((Map<String, Object>)obj, crmMap);
		} else {
			buildData4SyncOrderStatusFromPojo((WorkOrderT)obj, crmMap);
		}

		//以下三个字段在接口逻辑中赋值
		crmMap.put("stationNo", "");
		crmMap.put("phoneIMEI", "");
		crmMap.put("actionTime", "");

		crmMap.put("planMileage", "");

		crmMap.put("refuseReason", "");
		crmMap.put("directorName", user.getContact());
		crmMap.put("directorPhone", user.getPhone());
		crmMap.put("assistEngineerName", "");
		crmMap.put("engineerPhone", "");


		crmMap.put("travelMileage", "");
		crmMap.put("revisedMileage", "");

		crmMap.put("serviceCar", "");

		crmMap.put("drOrderNNo", "");
		crmMap.put("drDiagnoseReport", "");
		crmMap.put("doneSolutionList", new ArrayList<>());
		crmMap.put("faultInfo", "");
		crmMap.put("doneSolutionNoStr", "");
		crmMap.put("SMN", "");
		crmMap.put("remark", "");
		return crmMap;
	}

	// map = workOrder
	public void buildData4SyncOrderStatusFromMap(Map<String, Object> map, Map<String, Object> crmMap) {
		crmMap.put("orderNo", map.get("OrderNo"));
		crmMap.put("CCSSComplainerOrderNo", map.get("OrderNoCrm"));
		crmMap.put("CCSSOrderNo", map.get("CCSSOrderNo"));
//		crmMap.put("billStatus", map.get(""));
		crmMap.put("customerName", map.get("CustomerName"));
		crmMap.put("customerPhone", map.get("CustomerPhone"));
		crmMap.put("customerCompany", map.get("CustomerCompanyName"));
		crmMap.put("faultDesc", map.get("CustomerComplaint"));
		crmMap.put("positionLat", map.get("LocLat"));
		crmMap.put("positionLon", map.get("LocLon"));
		crmMap.put("location", map.get("Location"));
		crmMap.put("needGoOut", MapUtils.getIntValue(map, "IsOutside", 0));
	}

	public void buildData4SyncOrderStatusFromPojo(WorkOrderT order, Map<String, Object> crmMap) {
		crmMap.put("orderNo", order.getOrderNo());
		crmMap.put("CCSSComplainerOrderNo", order.getOrderNoCrm());
		crmMap.put("CCSSOrderNo", order.getCCSSOrderNo());
//		crmMap.put("billStatus", map.get(""));
		crmMap.put("customerName", order.getCustomerName());
		crmMap.put("customerPhone", order.getCustomerPhone());
		crmMap.put("customerCompany", order.getCustomerCompanyName());
		crmMap.put("faultDesc", order.getCustomerComplaint());
		crmMap.put("positionLat", order.getLocLat());
		crmMap.put("positionLon", order.getLocLon());
		crmMap.put("location", order.getLocation());
		crmMap.put("needGoOut", order.getIsOutside());
	}

	public Map<String, Object> bulidResolveRemoteData(Map<String, Object> map, WorkOrderT order) {
		Map<String, Object> retMap = new HashMap<>();
		retMap.put("orderNo", order.getOrderNo());
		retMap.put("CCSSComplainerOrderNo", StringUtils.isNotEmpty(order.getOrderNoCrm())?order.getOrderNoCrm():"");
		retMap.put("CCSSOrderNo", StringUtils.isNotEmpty(order.getCCSSOrderNo())?order.getCCSSOrderNo():"");
		retMap.put("isClaimant", map.get("IsCharged"));
		retMap.put("claimantDescription", map.get("ChargeDescription"));
		retMap.put("emoteSolutionType", map.get("ResolveReason")+(StringUtils.isBlank(MapUtils.getString(map, "Remark"))? "": ":"+MapUtils.getString(map, "Remark")));
		retMap.put("remark","");
		return retMap;
	}

	public Map<String, Object> createNewOrder(Map<String, Object> order, int status, Long stationId) {
		Map<String, Object> newOrder = new HashMap<>();
		newOrder.putAll(order);

		UserT user = UserThreadLocal.get();
		String currentTime = LocalTimeUtil.getRealCurrentTime();

		// 后台自动生成工单编号
		//String OrderNo =  SerialNumberUtil.getSerialNumber("WO");
		/**
		 * <p>
		 *     自动生成工单编号，由 redis 更改为 sqlServer
		 * </p>
		 */
		String OrderNo = OrderGenerateUtil.getWorkOrderNo();
		newOrder.put("OrderNo", OrderNo);
		//crm为空
		newOrder.put("OrderNoCrm", MapUtils.getString(order, "OrderNoCrm", ""));
		newOrder.put("ServiceStationId", stationId);
		newOrder.put("OrderStatus", status);
		//新工单绑定的新工单主键id
		newOrder.put("RelOrderId", "");
		//新工单绑定的旧工单的主键id
		newOrder.put("RelOrderIdOld", MapUtils.getLongValue(order, "ID"));
		//工单生成时间
//		newOrder.put("CreateTime", currentTime);
		//工单创建人ID
		newOrder.put("Creator",user.getId());
		// 工单更新人
		newOrder.put("Updator",user.getId());
		// 工单更新时间（修改工单判断条件之一）
		newOrder.put("UpdateTime",currentTime);

		newOrder.put("CCSSOrderNo",MapUtils.getString(order, "CCSSOrderNo", ""));
		newOrder.remove("GoOutType");// 生成的新工单需要去除出行方式字段
		newOrder.remove("ServiceCarId");// 生成的新工单需要去除服务车
		newOrder.remove("ServiceCarNo");// 生成的新工单需要去除服务车
		return newOrder;
	}

	public void saveOperation(Map<String, Object> map, Long processorId, String comment, String currentTime) {
		Map<String, Object> workOrderFlowTMap = new HashMap<String, Object>();  //新建工单操作记录对象
		workOrderFlowTMap.put("OrderId", MapUtils.getLong(map, "OrderId"));  //工单id
		workOrderFlowTMap.put("ProcessorId", processorId);  //处理人
		workOrderFlowTMap.put("OrderStatus", MapUtils.getIntValue(map, "OrderStatus"));  //工单状态
		workOrderFlowTMap.put("ProcessComment", comment);  //操作备注
		workOrderFlowTMap.put("ProLocLon", MapUtils.getFloatValue(map, "LocLon"));  //经度
		workOrderFlowTMap.put("ProLocLat", MapUtils.getFloatValue(map, "LocLat"));  //纬度
		workOrderFlowTMap.put("ProLocation", MapUtils.getString(map, "Location"));  //操作地点
		workOrderFlowTMap.put("IMEI", MapUtils.getString(map, "IMEI"));  //手机串号
		workOrderFlowTMap.put("Flag", 0);  //是否有效(0为是，1为否)
		workOrderFlowTMap.put("Creator",processorId);  //创建人
		workOrderFlowTMap.put("CreateTime", currentTime);  //处理时间
		workOrderRepairDao.saveOperation(workOrderFlowTMap);  //插入并保存工单操作记录数据
	}

}
